<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传者姓名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入上传者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="路径" prop="path">
        <el-input
          v-model="queryParams.path"
          placeholder="请输入路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:file:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:file:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          class="purple-button"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
        >打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          class="purple-button"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          @click="generateStatistics"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange" ref="fileTable" @sort-change="handleSort">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件ID" align="center" prop="fileId" sortable />
      <el-table-column label="项目ID" align="center" prop="projectId" sortable />
      <el-table-column label="上传者姓名" align="center" prop="username" />
      <el-table-column label="路径" align="center" prop="path" />
      <el-table-column label="文件名" align="center" prop="fileName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:file:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:file:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 统计对话框 -->
    <el-dialog title="上传者统计" :visible.sync="statisticsDialog" width="600px">
      <div class="statistics-container">
        <div v-for="(count, username) in ownerCounts" :key="username" class="bar" :style="{ width: (count * 30) + 'px' }">
          {{ username }}: {{ count }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statisticsDialog = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="上传者姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入上传者姓名" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog title="上传文件" :visible.sync="uploadDialog" width="600px">
      <el-form ref="uploadForm" :model="uploadForm" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="uploadForm.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="选择文件">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件名">
          <el-input v-model="uploadedFileName" placeholder="文件名" disabled />
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="uploadedFilePath" placeholder="文件路径" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmUpload">上传</el-button>
        <el-button @click="uploadDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/project/file";

export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传对话框
      uploadDialog: false,
      // 统计对话框
      statisticsDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        username: null,
        path: null,
        fileName: null,
        sortOrder: 'asc', // 新增排序字段
        sortBy: null // 新增排序字段
      },
      // 表单参数
      form: {},
      // 上传表单参数
      uploadForm: {
        projectId: null,
        file: null
      },
      // 上传后文件名和路径预览
      uploadedFileName: '',
      uploadedFilePath: '',
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "上传者姓名不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路径不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: true, message: "文件名不能为空", trigger: "blur" }
        ]
      },
      // 统计数据
      ownerCounts: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文档列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        projectId: null,
        username: null,
        path: null,
        fileName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 上传按钮操作 */
    handleUpload() {
      this.uploadDialog = true;
      this.uploadForm = {
        projectId: null,
        file: null
      };
      this.uploadedFileName = '';
      this.uploadedFilePath = '';
    },
    /** 文件选择变化 */
    handleFileChange(file) {
      this.uploadForm.file = file.raw; // 保存文件对象
      this.uploadedFileName = file.name; // 显示文件名
      this.uploadedFilePath = `uploads/${file.name}`; // 显示文件路径
    },
    /** 上传前的处理 */
    beforeUpload(file) {
      const isValid = ['application/pdf', 'application/msword', 'text/plain'].includes(file.type); // 允许的文件类型
      if (!isValid) {
        this.$message.error('上传文件只能是 PDF、DOC 或 TXT 格式!');
      }
      return isValid;
    },
    /** 确认上传 */
    confirmUpload() {
      if (!this.uploadForm.projectId || !this.uploadForm.file) {
        this.$message.error('请填写项目ID并选择文件!');
        return;
      }

      // 模拟文件上传
      const formData = new FormData();
      formData.append('file', this.uploadForm.file);
      formData.append('projectId', this.uploadForm.projectId);

      // 这里可以调用 API 上传文件
      // 假设上传成功后，生成上传者姓名、路径和文件名
      const username = '自动生成的用户名'; // 这里可以根据实际情况生成
      const fileName = this.uploadForm.file.name;

      // 生成新的文件ID
      const newFileId = this.fileList.length > 0 ? Math.max(...this.fileList.map(file => file.fileId)) + 1 : 1;

      // 更新表格数据
      this.fileList.push({
        fileId: newFileId, // 使用生成的文件ID
        projectId: this.uploadForm.projectId,
        username: username,
        path: this.uploadedFilePath,
        fileName: fileName
      });

      this.uploadDialog = false; // 关闭上传对话框
      this.$message.success('文件上传成功!');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids;
      getFile(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文档";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFile(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$confirm('是否确认删除文档编号为"' + fileIds + '"的数据项？').then(() => {
        return delFile(fileIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`);
    },
    /** 打印按钮操作 */
    handlePrint() {
      const printContent = this.$refs.fileTable.$el.cloneNode(true); // 克隆表格内容
      const printWindow = window.open('', '_blank'); // 打开新窗口
      printWindow.document.write('<html><head><title>打印文档</title>');
      printWindow.document.write('<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">'); // 引入样式
      printWindow.document.write('</head><body>');
      printWindow.document.write(printContent.outerHTML); // 写入表格内容
      printWindow.document.write('</body></html>');
      printWindow.document.close(); // 关闭文档
      printWindow.print(); // 调用打印
      printWindow.close(); // 关闭打印窗口
    },
    /** 处理排序请求 */
    handleSort({ prop, order }) {
      this.queryParams.sortBy = prop;
      this.queryParams.sortOrder = order === 'ascending' ? 'asc' : 'desc';
      this.getList(); // 重新获取列表以应用排序
    },
    /** 生成统计数据 */
    generateStatistics() {
      const ownerCounts = {};
      this.fileList.forEach(file => {
        ownerCounts[file.username] = (ownerCounts[file.username] || 0) + 1;
      });

      this.ownerCounts = ownerCounts;
      this.statisticsDialog = true;
    }
  }
};
</script>

<style>
.statistics-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.bar {
  height: 30px;
  margin: 5px 0;
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  transition: width 0.3s;
}
</style>
